/*
 * @Author: Sonui
 * @Date: 2022-02-23 00:06:37
 * @LastEditors: Sonui
 * @LastEditTime: 2022-02-23 05:14:20
 * @FilePath: \AI_SCHEDULE\Provider.js
 * @Description: 从前端获取必要课程的信息
 * email: me@sonui.cn
 * Copyright (c) 2022 by Sonui, All Rights Reserved. 
 */

/**
 * @description: 
 * @param {*} data 关联数组
 * @return {*} 返回拼接后的form-data
 */
function urlEncode(data) {
    let ret = "";
    for (key in data)
        ret += "&" + key + "=" + encodeURIComponent(data[key])
    return ret;
}

/**
 * @description: 从网页代码中根据属性名提取属性值
 * @param {*} bodyStr 网页代码
 * @param {*} name 属性名称
 * @return {*} 属性值
 */
function getRollInfo(bodyStr, name) {
    let regexp = new RegExp("profile-info-name\">" + name + "<[\\s\\S]+?>(\\S+?)<"),
        ret = regexp.exec(bodyStr);
    if (ret == null) return '';
    return ret[1];
}

/**
 * @description: 在用户设备获取课程信息并返回
 * @param {*} iframeContent 不知道干啥的，小爱写死的
 * @param {*} frameContent 不知道干啥的，小爱写死的
 * @param {*} dom 不知道干啥的，小爱写死的
 * @return {*} 返回课程JSON格式字符串信息
 */
async function scheduleHtmlProvider(iframeContent = '', frameContent = '', dom = document) {
    await loadTool('AIScheduleTools')
    let response;
    /*
        学院代码和专业代码写死，有变更手动更新下
        通过接口查询也是个方法，但多个网络请求不舒服

        type: GET
        url: http://110.16.109.224:82/student/teachingResources/gradeAndClassCurriculum/subjectJson?departmentNum={学院代码}
        response:[{
                    "subjectCode": "08",
                    "subjectName": "英语",
                    "subjectName_en": "English",
                    "departmentNum": "06",
                    "professionalProfile": null
                }]
    */
    /*********************学院代码**********************/
    const departmentCodeList = {
        "艺术学院": "01",
        "语言与传媒学院": "02",
        "信息工程学院": "03",
        "交通与环境学院": "04",
        "商学院": "05",
        "外国语学院": "06"
    };

    /*********************专业代码**********************/
    const subjectCodeList = {
        "计算机科学与技术": "02",
        "信息与计算科学": "03",
        "通信工程": "09",
        "电子信息科学与技术": "16",
        "自动化": "19",
        "软件工程": "29",
        "绘画": "06",
        "艺术设计": "07",
        "动画": "13",
        "视觉传达设计": "20",
        "环境设计": "21",
        "产品设计": "22",
        "服装与服饰设计": "23",
        "新闻学": "04",
        "新闻学(播音与主持艺术)": "05",
        "汉语言文学": "14",
        "表演": "25",
        "播音与主持艺术": "27",
        "土木工程": "01",
        "环境科学": "12",
        "汽车服务工程": "26",
        "工程管理": "28",
        "环境工程": "30",
        "会计学": "10",
        "人力资源管理": "15",
        "财务管理": "17",
        "金融学": "18",
        "电子商务": "24",
        "英语": "08",
        "日语": "11"
    };

    /*********************获取登录账号学籍信息，为后续接口请求提供参数**********************/
    let year, department, subject, classCode;
    response = await fetch("http://110.16.109.224:82/student/rollManagement/rollInfo/index", {
        "headers": {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "proxy-connection": "keep-alive",
            "upgrade-insecure-requests": "1"
        },
        "referrer": "http://110.16.109.224:82/student/courseSelect/calendarSemesterCurriculum/index",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": null,
        "method": "GET",
        "mode": "cors",
        "credentials": "same-origin"
    });
    response = await response.text();
    //处理掉换行和制表符
    response = response.replaceAll("\r", "");
    response = response.replaceAll("\n", "");
    response = response.replaceAll("\t", "");

    department = getRollInfo(response, "院系");
    subject = getRollInfo(response, "专业");
    year = getRollInfo(response, "年级").replaceAll("级", "");
    classCode = getRollInfo(response, "班级	");
    classCode = classCode.substring(classCode.length - 2, classCode.length - 1);

    classCode = year.substring(2, 4) + subjectCodeList[subject] + (/\d+/.test(classCode) ? classCode : '1');

    if (department == null || subject == null || year == null || classCode.length != 5) {
        await AIScheduleAlert("获取学生信息错误，请等待适配更新后再次尝试导入")
        return 'do not continue'
    }
    /*********************查询班级课表列表**********************/
    //初始化请求参数
    let sendData = {
        "param_value": 100011,
        "schoolName": "内蒙古大学创业学院",
        "executiveEducationPlanNum": "",
        "yearNum": year,
        "departmentNum": departmentCodeList[department],
        "subjectNum": subjectCodeList[subject],
        "classNum": classCode,
        "pageNum": 1,
        "pageSize": 30
    }

    console.log("sendData", sendData);
    response = await fetch("http://110.16.109.224:82/student/teachingResources/classCurriculum/search", {
        "headers": {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache'
        },
        "referrer": "http://110.16.109.224:82/student/teachingResources/classCurriculum/index",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": urlEncode(sendData),
        "method": "POST",
        "mode": "cors",
        "credentials": "same-origin"
    });
    response = await response.text();
    response = JSON.parse(response);
    response = response[0];

    let list = new Array();
    for (let i = 0; i < response.records.length; i++)
        list[i] = response.records[i].executiveEducationPlanName


    /*********************咨询导入哪学期课表**********************/
    if (list.length == 0) {
        await AIScheduleAlert("班级课表列表解析失败，请等待适配更新后再次尝试导入")
        return 'do not continue'
    }

    const userSelect = await AIScheduleSelect({
        titleText: '提示',
        contentText: '请选择想要导入的学期课表，秋为上半学年，春为下半学年``该处数据来源: 教学资源→班级课表',
        selectList: list,
    });

    /*********************查询课表详情**********************/
    let zxjxjhh;
    for (let i = 0; i < response.records.length; i++)
        if (response.records[i].executiveEducationPlanName == userSelect)
            zxjxjhh = response.records[i].zxjxjhh;

    response = await fetch("http://110.16.109.224:82/student/teachingResources/classCurriculum/searchCurriculumInfo/callback?planCode=" + zxjxjhh + "&classCode=" + classCode, {
        "headers": {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "proxy-connection": "keep-alive",
            "x-requested-with": "XMLHttpRequest"
        },
        "referrer": "http://110.16.109.224:82/student/teachingResources/classCurriculum/index",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": null,
        "method": "GET",
        "mode": "cors",
        "credentials": "same-origin"
    });
    response = await response.text();
    return response;
}